<?php

namespace App\Http\Controllers\Backend\Orders;

use App\ConstDir\ErrorConst;
use App\Http\Controllers\Backend\BaseController;
use App\Repository\Criteria\Orders\FormalOrderCriteria;
use App\Repository\Criteria\Orders\TestOrderCriteria;
use App\Repository\Models\Orders;
use App\Repository\Repositories\Interfaces\ExamplesRepository;
use App\Repository\Repositories\Interfaces\OrdersRepository;
use Illuminate\Http\Request;
use Prettus\Repository\Criteria\RequestCriteria;

/**
 * 订单管理控制器
 *
 * @package App\Http\Controllers\Backend
 */
class OrdersController extends BaseController
{
    /**
     * @var OrdersRepository
     */
    protected $orders_repo;

    const SOURCE_FORMAL = 'formal'; //包含正式订单与刷单
    const SOURCE_TEST = 'test'; //测试订单
    const SOURCE_ALL = 'all'; //全部订单

    public function __construct(OrdersRepository $orders_repo, Request $request)
    {
        $this->orders_repo = $orders_repo;

        $source = $request->get('source', self::SOURCE_FORMAL);
        if ($source == self::SOURCE_FORMAL) { //正常订单
            $this->orders_repo->pushCriteria(app(FormalOrderCriteria::class));
        } elseif ($source == self::SOURCE_TEST) {  //测试订单
            $this->orders_repo->pushCriteria(app(TestOrderCriteria::class));
        } elseif ($source == self::SOURCE_ALL) {
            //所有订单
        }
//        $this->orders_repo->scopeQuery(function ($query) {
//            return $query->where('order_type','!=' ,6);// 区分普通订单 和 服务订单
//        });
    }

    public function index(Request $request)
    {
        $orders = $this->orders_repo->with(['shop', 'user', 'orderProducts'])->paginate($this->perPage);
        return $this->success(ErrorConst::SUCCESS_CODE, $orders, true);
    }

    public function show($id)
    {
        $order = $this->orders_repo->with(['shop', 'user', 'orderProducts', 'orderExpress'])->find($id);
        return $this->success(ErrorConst::SUCCESS_CODE, $order['data']);
    }

    public function store()
    {
        //后台无订单创建
    }

    public function update(Request $request, $id)
    {
        $this->validate($request, [
            'order_status' => 'integer|in:' . Orders::ORDER_STATUS_CANCEL,
        ]);
        $data = $request->all(['order_status']);

        $ret = $this->orders_repo->update($data, $id);
        if ($ret) {
            return $this->success(ErrorConst::SUCCESS_CODE_MSG, ErrorConst::SUCCESS_CODE);
        } else {
            return $this->error(ErrorConst::FAILED_CODE_MSG);
        }
    }

    public function delete($id)
    {
        //暂不开放删除接口
        return $this->error(ErrorConst::FAILED_CODE);

        $ret = $this->orders_repo->delete($id);

        if ($ret) {
            return $this->success(ErrorConst::SUCCESS_CODE, ErrorConst::SUCCESS_CODE_MSG);
        } else {
            return $this->error(ErrorConst::FAILED_CODE);
        }
    }
}
